"""
闹钟管理模块 - 处理闹钟的创建、编辑、删除和触发逻辑
"""
import json
import os
import threading
import time
from datetime import datetime, timedelta


class AlarmManager:
    def __init__(self, config_file="alarms_config.json"):
        """初始化闹钟管理器"""
        self.config_file = config_file
        self.alarms = []
        self.running = False
        self.checker_thread = None
        self.alarm_callback = None
        
        # 加载保存的闹钟
        self.load_alarms()
    
    def add_alarm(self, hour, minute, repeat_mode, custom_days=None, ringtone="", enabled=True):
        """添加新闹钟"""
        alarm = {
            "hour": hour,
            "minute": minute,
            "repeat": repeat_mode,
            "custom_days": custom_days or [],
            "ringtone": ringtone,
            "enabled": enabled
        }
        self.alarms.append(alarm)
        self.save_alarms()
        return len(self.alarms) - 1
    
    def edit_alarm(self, index, hour, minute, repeat_mode, custom_days=None, ringtone="", enabled=True):
        """编辑现有闹钟"""
        if 0 <= index < len(self.alarms):
            self.alarms[index] = {
                "hour": hour,
                "minute": minute,
                "repeat": repeat_mode,
                "custom_days": custom_days or [],
                "ringtone": ringtone,
                "enabled": enabled
            }
            self.save_alarms()
            return True
        return False
    
    def delete_alarm(self, index):
        """删除闹钟"""
        if 0 <= index < len(self.alarms):
            del self.alarms[index]
            self.save_alarms()
            return True
        return False
    
    def toggle_alarm(self, index):
        """切换闹钟启用/禁用状态"""
        if 0 <= index < len(self.alarms):
            self.alarms[index]["enabled"] = not self.alarms[index]["enabled"]
            self.save_alarms()
            return self.alarms[index]["enabled"]
        return None
    
    def get_alarm(self, index):
        """获取指定闹钟"""
        if 0 <= index < len(self.alarms):
            return self.alarms[index].copy()
        return None
    
    def get_all_alarms(self):
        """获取所有闹钟"""
        return [alarm.copy() for alarm in self.alarms]
    
    def save_alarms(self):
        """保存闹钟到文件"""
        try:
            # 移除临时字段
            alarms_to_save = []
            for alarm in self.alarms:
                alarm_copy = alarm.copy()
                if '_last_played' in alarm_copy:
                    del alarm_copy['_last_played']
                alarms_to_save.append(alarm_copy)
            
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump({"alarms": alarms_to_save}, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存闹钟失败: {e}")
    
    def load_alarms(self):
        """从文件加载闹钟"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    self.alarms = data.get("alarms", [])
        except Exception as e:
            print(f"加载闹钟失败: {e}")
            self.alarms = []
    
    def start_checking(self, callback):
        """启动闹钟检查线程"""
        self.alarm_callback = callback
        self.running = True
        self.checker_thread = threading.Thread(target=self._check_alarms_loop, daemon=True)
        self.checker_thread.start()
    
    def stop_checking(self):
        """停止闹钟检查"""
        self.running = False
        if self.checker_thread:
            self.checker_thread.join(timeout=2)
    
    def _check_alarms_loop(self):
        """闹钟检查循环（在后台线程中运行）"""
        while self.running:
            try:
                now = datetime.now()
                current_time = (now.hour, now.minute)
                current_weekday = now.weekday()  # 0=周一, 6=周日
                
                for alarm in self.alarms:
                    if not alarm["enabled"]:
                        continue
                    
                    alarm_time = (alarm["hour"], alarm["minute"])
                    
                    # 检查时间是否匹配
                    if current_time != alarm_time:
                        continue
                    
                    # 检查是否已经在这一分钟内播放过
                    current_minute_key = now.strftime("%Y-%m-%d %H:%M")
                    if alarm.get('_last_played') == current_minute_key:
                        continue
                    
                    # 检查重复模式
                    should_trigger = self._should_trigger_alarm(alarm, current_weekday)
                    
                    if should_trigger:
                        alarm['_last_played'] = current_minute_key
                        
                        # 如果是一次性闹钟，触发后禁用
                        if alarm["repeat"] == "一次":
                            alarm["enabled"] = False
                            self.save_alarms()
                        
                        # 调用回调函数
                        if self.alarm_callback:
                            self.alarm_callback(alarm.copy())
                
                time.sleep(1)  # 每秒检查一次
            except Exception as e:
                print(f"闹钟检查错误: {e}")
                time.sleep(1)
    
    def _should_trigger_alarm(self, alarm, current_weekday):
        """判断闹钟是否应该触发"""
        repeat_mode = alarm["repeat"]
        
        if repeat_mode == "一次":
            return True
        elif repeat_mode == "每天":
            return True
        elif repeat_mode == "工作日":
            return current_weekday < 5  # 周一到周五
        elif repeat_mode == "周末":
            return current_weekday >= 5  # 周六和周日
        elif repeat_mode == "自定义":
            day_names = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
            current_day = day_names[current_weekday]
            return current_day in alarm.get("custom_days", [])
        
        return False
    
    def create_snooze_alarm(self, original_alarm, snooze_minutes=5):
        """创建稍后提醒闹钟"""
        snooze_time = datetime.now() + timedelta(minutes=snooze_minutes)
        return self.add_alarm(
            hour=snooze_time.hour,
            minute=snooze_time.minute,
            repeat_mode="一次",
            custom_days=[],
            ringtone=original_alarm.get("ringtone", ""),
            enabled=True
        )
    
    def get_next_alarm_time(self):
        """获取下一个将要触发的闹钟时间"""
        if not self.alarms:
            return None
        
        now = datetime.now()
        next_alarm = None
        min_delta = None
        
        for alarm in self.alarms:
            if not alarm["enabled"]:
                continue
            
            # 计算今天的闹钟时间
            alarm_time = now.replace(hour=alarm["hour"], minute=alarm["minute"], second=0, microsecond=0)
            
            # 如果今天的时间已过，检查明天及以后
            if alarm_time <= now:
                alarm_time += timedelta(days=1)
            
            # 检查重复模式
            for days_ahead in range(8):  # 检查未来7天
                check_time = alarm_time + timedelta(days=days_ahead)
                weekday = check_time.weekday()
                
                if self._should_trigger_alarm(alarm, weekday):
                    delta = check_time - now
                    if min_delta is None or delta < min_delta:
                        min_delta = delta
                        next_alarm = check_time
                    break
        
        return next_alarm
